<template>
  <canvas
    class="canvas"
    id="myCanvas2"
    ref="canvasRef"
    :style="{
      top: props.top + 'px',
      left: props.left + 'px',
    }"
    @click="onMouseClick"
    v-show="props.isEdit"
  ></canvas>
</template>
<script setup>
import { ref, watch, onMounted, nextTick, inject } from "vue";
import {
  AmbientLight,
  Box3,
  Camera,
  Color,
  DirectionalLight,
  Euler,
  Group,
  Light,
  LoadingManager,
  Material,
  Matrix4,
  Mesh,
  Raycaster,
  MeshBasicMaterial,
  MeshStandardMaterial,
  Object3D,
  OrthographicCamera,
  PMREMGenerator,
  PerspectiveCamera,
  REVISION,
  Scene,
  Texture,
  GridHelper,
  Vector3,
  Vector2,
  WebGLRenderer,
} from "three";
import Viewer from "./view2.js";
// import * as THREE from "three";
// import { OBJLoader, MTLLoader } from "three-obj-mtl-loader"; //obj
// import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader"; //gltf
// import { OrbitControls } from "three/examples/jsm/controls/OrbitControls"; //gltf
// import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";
import { More } from "@element-plus/icons-vue";
import { PRESET_COLOR } from "./color";
//
// :style="{
//       top: props.top + 'px',
//       left: props.left + 'px',
//     }"
const props = defineProps({
  colorType: {
    type: Boolean,
    default: false,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
  top: {
    type: String,
    default: "",
  },
  left: {
    type: String,
    default: "",
  },
  activeCanvas: {
    type: Number,
  },
});
const emits = defineEmits(["getSceneLength", "getImgData", "getMaterialData"]);
const scenesData = ref();
const viewScenes = ref();
const materials = ref([]);
const colorize = ref(false);
const isEdit = ref(false);
const loading = ref(false);
const canvasRef = ref(null);
const viewer = ref(null);
const tableData = ref([]);
const imgData = ref([]);
const colorsMap = ref();
const activeCamera = ref();
// viewer.value = new Viewer(canvasRef.value, {});
onMounted(() => {
  nextTick(() => {
    if (canvasRef.value) {
      viewer.value = new Viewer(canvasRef.value, {});
    }
    colorize.value = props.colorType;
    load();
  });
  document.getElementById("myCanvas2").addEventListener("click", (event) => {});
});
watch(
  () => props.activeCanvas,
  (newV) => {
    if (newV) {
      if (!viewer) return;
      console.log("前台改变canvas监听到了", newV);
      viewer.value.setCurrent(newV);
    }
  }
);
const onMouseClick = async (event) => {
  const [material, color] = await viewer.value.getMaterial(event);
  console.log("onMouseClick", material, color);
  emits("getMaterialData", { material, color });
  // console.log("onMouseClick", material, color);
};
const load = () => {
  loading.value = true;
  const fileURL =
    "https://assets.youcl.com.cn/model19_ed16acbbc869430c162ce4b465741d3b";
  // if (fileURL) {
  fetchBlob(fileURL)
    .then((blob) => {
      // 在这里处理Blob对象
      const reader = new FileReader();
      reader.onload = async function (event) {
        // const fileURL = event.target?.result;

        if (!viewer) return;
        if (!fileURL) return;
        try {
          let testUrl = URL.createObjectURL(blob);
          const [gltf, materials] = await viewer.value.load(testUrl);

          // const [gltf, materials] = await viewer.value.load(fileURL);
          scenesData.value = gltf.cameras?.length
            ? gltf.cameras
            : viewer.presetCameras;
          emits("getSceneLength", scenesData.value.length);
          materials.value = materials;
          activeCamera.value = scenesData.value[1];
          // viewer.value.render("3333");
          const [colors, scenes] = await viewer.value.init(
            scenesData.value.length
          );
          console.log("colors", colors, scenes);
          colorsMap.value = colors;
          viewScenes.value = scenes;
          // viewer.value.createControls();
          imgData.value = viewer.value.imgData;
          emits("getImgData", viewer.value.imgData);
        } catch (err) {
          console.log(err);
        } finally {
          loading.value = false;
        }
      };
      // reader.readAsData(fileURL);
      reader.readAsDataURL(blob);
    })
    .catch((error) => {
      console.error("Error fetching and converting blob:", error);
    });

  // }
};

function fetchBlob(url) {
  return fetch(url)
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
      return response.blob();
    })
    .catch((error) => {
      console.error("Fetch error:", error);
    });
}
const download = () => {
  const dataURL = window.renderer.domElement.toDataURL("image/jpg");
  const link = document.createElement("a");
  link.href = dataURL;
  link.download = "image.jpg";
  link.click();
};
const onPage = (isPrev) => {
  if (!viewer) return;
  if (scenesData.value.length < 0) return;
  const page = viewer.value.state.page;
  if (isPrev) {
    viewer.value.state.page = page - 1 < 0 ? 0 : page - 1;
  } else {
    viewer.value.state.page =
      page + 1 > scenesData.value.length - 1
        ? scenesData.value.length - 1
        : page + 1;
  }
  colorize.value = false;
  viewer.value.render(true);
};
watch(viewer, (newV) => {
  if (newV) return;
  const el = canvasRef.value;
  if (el) {
    viewer.value = new Viewer(el, {});
  }
});
watch([colorize, viewer], (newV) => {
  if (!newV[1]) return;
  viewer.value.render(true);
});
</script>
<style lang="scss" scoped>
.loading {
  position: fixed;
  left: 0;
  top: 0;
}

.canvas {
  /* width: calc(100vw - 200px);
  height: 100vh; */
  width: 420px;
  //width: 100%;
  // height: 440px;
  // opacity: 0;
  box-sizing: border-box;
  position: absolute;
  z-index: 99;
}

.panel {
  width: 200px;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  padding: 0 12px;
  box-sizing: border-box;
  box-shadow: -1px 0 3px 0 #000;
  position: absolute;
  right: 0;
  top: 0;
  z-index: 9999;
}

.file,
.page {
  width: 100%;
  height: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.colorize {
  width: 100%;
  height: 32px;
  line-height: 32px;
  padding: 0;
  font-size: 12px;
  outline: none;
  border: none;
  margin-top: 4px;
  opacity: 0.8;
  transition: all 200ms linear;
}

.colorize:hover {
  opacity: 1;
}
.report-ppt-item {
  width: 840px;
  // height: 1200px;
  height: 594px;
  background: #fff;
  border-radius: 20px;
  margin-top: 40px;
  margin: 40px auto;
  // display: block !important;
  .container {
    width: 100%;
    height: 520px;
    // padding-right: 200px;
    // box-sizing: border-box;
    display: flex;
    .canvas-wrap {
      width: 420px;
      //width: 100%;
      height: 500px;
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 20px;
      margin-top: 0;
      border: 1px dashed #e0e0e0;
      position: relative;
      .edit-btn {
        position: absolute;
        top: -10px;
        left: 250px;
        display: none;
      }
      &:hover {
        .edit-btn {
          display: block;
        }
      }
    }
  }
  .page-title {
    padding: 20px;
    text-align: left;
    padding-left: 50px;
    font-size: 22px;
    font-weight: bold;
    color: #ba6b10;
  }
}
.palette {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: auto;
}

#upload {
  display: none;
}

.upload,
.download {
  width: 80px;
  height: 32px;
  line-height: 32px;
  padding: 0;
  text-align: center;
  font-size: 12px;
  display: block;
  background-color: #000;
  border: none;
  outline: none;
  border-radius: 4px;
  opacity: 0.8;
  cursor: pointer;
  transition: all 200ms linear;
}
.download {
  right: 20px;
}

.upload:hover,
.download:hover {
  opacity: 1;
}

.prev,
.next {
  width: 80px;
  height: 32px;
  line-height: 32px;
  text-align: center;
  padding: 0;
  font-size: 12px;
  transition: all 200ms linear;
  opacity: 0.8;
  border: none;
  outline: none;
}
.prev:hover,
.next:hover {
  opacity: 1;
}

.prev {
  right: 120px;
}

.row {
  width: 100%;
  height: 20px;
  margin: 4px 0;
  display: flex;
  box-sizing: border-box;
}

.color {
  display: block;
  width: 60px;
  height: 20px;
  border-radius: 4px;
}

.label {
  display: block;
  color: #000;
  font-size: 12px;
  flex: 1;
  margin: 0 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
